import hashlib

from web3 import Web3


def base10toN(num, n):
    """Change a to a base-n number.
    Up to base-36 is supported without special notation."""
    table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_!@#$%^&*()+=[]{},.;:·~<>?|'
    table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'*200
    print("len(table)", len(table), n)
    num_rep = dict([(k, v) for k, v in enumerate(table)])
    new_num_string = ''
    current = num
    while True:
        remainder = int(current % n)
        new_num_string = num_rep[remainder] + new_num_string

        # print(current - remainder)
        # 使用 current/n 丢失精度
        current = divmod(current, n)[0]
        if current == 0:
            break

    return new_num_string


def baseNto10(num_str, base):
    table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
    num_rep = dict([(v, n) for n, v in enumerate(table)])

    result = 0
    for i in range(len(num_str)):
        result *= base
        result += num_rep[num_str[i]]
    return result


if __name__ == '__main__':
    # from passlib.hash import hex_md5 等同
    m1 = hashlib.md5('MINTER_ROLE'.encode(encoding='utf-8'))
    m2 = m1.hexdigest()

    # from passlib.hash import hex_sha256
    print(hashlib.sha256('MINTER_ROLE'.encode(encoding='utf-8')).hexdigest())
    m3 = Web3.toInt(hexstr=f'0x{m2}')
    print("[hex to int]", int(m2, 16))
    print("[hex to int]", m3)
    print("[hex]", m2)

    print(base10toN(m3, 90))
    print(base10toN(m3, 12400))
    print(baseNto10("d5a1bdbed2ab836c3527435bcf8247d6", 16))
    print(baseNto10(base10toN(m3, 63), 63))

    # solidity > keccak256("MINTER_ROLE")
    print(Web3.sha3(text='MINTER_ROLE').hex())
    print(Web3.keccak(text='MINTER_ROLE').hex())
